﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Think9.Models;
using Think9.Services.Base;
using Think9.Services.Basic;

namespace Think9.Controllers.Basic
{
    [Area("SysTable")]
    public class IndexBasicController : BaseController
    {
        private ComService ComService = new ComService();
        private IndexBasicService IndexBasicService = new IndexBasicService();
        private SortService SortService = new SortService();
        private IndexDateType IndexDtaeTypeService = new IndexDateType();

        //指标分类
        private SelectList SortList
        { get { return new SelectList(SortService.GetAll("ClassID,SortID,SortName", "ORDER BY SortOrder").Where(x => x.ClassID == "CAT_index"), "SortID", "SortName"); } }

        //指标类型
        private SelectList IndexDtaeTypeList
        { get { return new SelectList(IndexDtaeTypeService.GetIndexDtaeType(), "TypeId", "TypeName"); } }

        [HttpGet]
        public override ActionResult Index(int? id)
        {
            ViewBag.DtaeTypeList = IndexDtaeTypeList;
            ViewBag.IndexSortList = SortList;

            base.Index(id);
            return View();
        }

        [HttpGet]
        public ActionResult Add(string frm)
        {
            ViewBag.frm = string.IsNullOrEmpty(frm) ? "" : frm;
            ViewBag.SortList = SortList;
            ViewBag.DtaeTypeList = IndexDtaeTypeService.GetIndexDtaeType();

            return View();
        }

        [HttpPost]
        public ActionResult Add(IndexBasicEntity model)
        {
            string sErr = "";
            string str01 = "#dex#dexes#file#ner#out#sensitive#sert#teger#t#t1#t2#t3#t4#t5#t6#t7#t8#t9#terval#to#terval#serttext#teger1#teger2#teger3#teger4#tersect#terface#ternal#";
            string str02 = "#index#indexes#infile#inner#inout#insensitive#insert#integer#int#int1#int2#int3#int4#int5#int6#int7#int8#int9#interval#into#interval#inserttext#integer1#integer2#integer3#integer4#intersect#interface#internal#";

            if (model.IndexId.ToLower().StartsWith("sys"))
            {
                sErr += "编码不能sys开头 ";
            }

            if (model.IndexId.ToLower().StartsWith("tb"))
            {
                sErr += "编码不能tb开头 ";
            }

            if (str01.Contains("#" + model.IndexId.ToLower() + "#"))
            {
                sErr += "编码不能为以下关键字:" + str01.Replace("#", " ");
            }

            if (str02.Contains("#" + model.IndexId.ToLower() + "#"))
            {
                sErr += "编码不能为以下关键字:" + str02.Replace("#", " ");
            }

            if (sErr != "")
            {
                var result = ErrorTip(sErr);
                return Json(result);
            }
            else
            {
                if (!model.IndexId.ToLower().StartsWith("in"))
                {
                    model.IndexId = "in" + model.IndexId;//指标前缀
                }
                model.UpdateTime = DateTime.Now;

                string where = "where IndexId=@IndexId";
                if (ComService.GetTotal("IndexBasic", where, new { IndexId = model.IndexId }) > 0)
                {
                    var result = ErrorTip("添加失败!已存在相同指标编码");
                    return Json(result);
                }
                else
                {
                    IndexDtaeTypeEntity IndexDtaeType = IndexDtaeTypeService.GetByWhereFirst("where TypeId=@TypeId", new { TypeId = model.IndexDataType });
                    if (IndexDtaeType != null)
                    {
                        model.Mlen = IndexDtaeType.Mlen;
                        model.Digit = IndexDtaeType.Digit;

                        var result = IndexBasicService.Insert(model) ? SuccessTip("操作成功") : ErrorTip("操作失败");
                        return Json(result);
                    }
                    else
                    {
                        var result = ErrorTip("添加失败!指标类型错误");
                        return Json(result);
                    }
                }
            }
        }

        [HttpGet]
        public ActionResult Edit(string id)
        {
            ViewBag.SortList = SortList;
            ViewBag.DtaeTypeList = IndexDtaeTypeService.GetIndexDtaeType();

            var model = IndexBasicService.GetByWhereFirst("where IndexId=@IndexId", new { IndexId = id });
            if (model != null)
            {
                return View(model);
            }
            else
            {
                return Json("数据不存在！");
            }
        }

        [HttpPost]
        public ActionResult Edit(IndexBasicEntity model)
        {
            model.UpdateTime = DateTime.Now;

            string where = "where IndexId='" + model.IndexId + "'";
            string updateFields = "IndexSort,IndexName,IndexExplain,UpdateTime";

            var result = IndexBasicService.UpdateByWhere(where, updateFields, model) > 0 ? SuccessTip("操作成功") : ErrorTip("编辑失败");
            return Json(result);
        }

        [HttpPost]
        public ActionResult GetIndexList(IndexBasicEntity model, PageInfoEntity pageInfo, string key, string sort, string type)
        {
            string _tbname;
            string _sort = sort == null ? "" : sort; ;
            string _datetype = type == null ? "" : type; ;
            string _keywords = key == null ? "" : key;

            pageInfo.returnFields = "IndexSort,IndexDataType,IndexId,IndexName,IndexExplain";
            pageInfo.field = " UpdateTime desc";

            string where = "where 1=1 ";
            if (_sort != "")
            {
                where += " and IndexSort=@IndexSort ";
                model.IndexSort = _sort;
            }

            if (_datetype != "")
            {
                where += " and IndexDataType=@IndexDataType ";
                model.IndexDataType = _datetype;
            }

            if (_keywords != "")
            {
                where += " and (IndexId like @IndexId OR IndexName like @IndexName) ";
                model.IndexId = string.Format("%{0}%", _keywords);
                model.IndexName = string.Format("%{0}%", _keywords);
            }

            long total = 0;
            IEnumerable<dynamic> list = IndexBasicService.GetPageByFilter(ref total, model, pageInfo, where);

            string sql = "select * from sys_datatype";
            DataTable dt = ComService.GetDataTable(sql);

            sql = "select * from sys_sort where ClassID='CAT_index' ORDER BY SortOrder";
            DataTable dt2 = ComService.GetDataTable(sql);

            sql = @"SELECT a.TbId,a.IndexId,a.IndexName,b.TbName FROM tbindex a
                           INNER JOIN tbbasic b ON a.TbId=b.TbId ORDER BY TbId ASC";
            DataTable dt3 = ComService.GetDataTable(sql);

            foreach (Object obj in list)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    if (dr["TypeId"].ToString() == ((IndexBasicEntity)obj).IndexDataType)
                    {
                        ((IndexBasicEntity)obj).DataTypeName = dr["TypeName"].ToString();
                    }
                }

                foreach (DataRow dr in dt2.Rows)
                {
                    if (dr["SortID"].ToString() == ((IndexBasicEntity)obj).IndexSort)
                    {
                        ((IndexBasicEntity)obj).IndexSort = dr["SortName"].ToString();
                    }
                }

                _tbname = "";
                foreach (DataRow dr in dt3.Select("IndexId='" + ((IndexBasicEntity)obj).IndexId + "'"))
                {
                    if (dr["IndexId"].ToString() == ((IndexBasicEntity)obj).IndexId)
                    {
                        _tbname += "{" + dr["TbName"].ToString() + "}  ";
                    }
                }
                ((IndexBasicEntity)obj).TableName = _tbname;
            }

            var result = new { code = 0, msg = "", count = total, data = list };

            return Json(result);
        }

        [HttpPost]
        public ActionResult GetIndexListBySearch(IndexBasicEntity model, PageInfoEntity pageInfo, string key, string sort, string type, string show, string tbid)
        {
            string _sort = sort == null ? "" : sort; ;
            string _datetype = type == null ? "" : type; ;
            string _keywords = key == null ? "" : key;
            string _show = show == null ? "" : show;
            string _tbid = tbid == null ? "" : tbid;
            if (!_tbid.StartsWith("tb_"))
            {
                _tbid = "tb_" + _tbid;
            }

            pageInfo.returnFields = "IndexSort,IndexDataType,IndexId,IndexName,IndexExplain";
            pageInfo.field = " order by UpdateTime desc";

            string where = "where 1=1 ";
            if (_sort != "")
            {
                where += " and IndexSort=@IndexSort ";
                model.IndexSort = _sort;
            }

            if (_datetype != "")
            {
                if(_datetype.Length == 1)
                {
                    where += " and left(IndexDataType, 1)=@IndexDataType ";
                }
                else
                {
                    where += " and IndexDataType=@IndexDataType ";
                }
                model.IndexDataType = _datetype;
            }

            if (_keywords != "")
            {
                where += " and (IndexId like @IndexId OR IndexName like @IndexName) ";
                model.IndexId = string.Format("%{0}%", _keywords);
                model.IndexName = string.Format("%{0}%", _keywords);
            }

            long total = 0;

            IEnumerable<dynamic> list = IndexBasicService.GetByWhere(where, model);

            List<IndexBasicEntity> newlist = IndexBasicService.GetIndexListBySearch(list, _tbid, _show);

            //total = ComService.GetTotal("IndexBasic", where);
            //DataTable dt = ComService.GetDataTablePageList("IndexBasic", pageInfo.returnFields, where, pageInfo.field, pageInfo.page, pageInfo.limit, model);

            var result = new { code = 0, msg = "", count = 999999, data = newlist };

            return Json(result);
        }

        [HttpGet]
        public JsonResult Delete(string id)
        {
            string where = "where IndexId='" + id + "'";
            string str = "";
            bool bExit = false;

            if (ComService.GetTotal("TbIndex", where) > 0)
            {
                bExit = true;
                str = "录入指标删除失败！还有与其关联的录入表";
            }

            if (!bExit)
            {
                where = "where IndexId='" + id + "'";
                var result = IndexBasicService.DeleteByWhere(where) ? SuccessTip("删除成功") : ErrorTip("操作失败");
                return Json(result);
            }
            else
            {
                return Json(ErrorTip(str));
            }
        }

        [HttpGet]
        public JsonResult BatchDel(string idsStr)
        {
            string str = "";
            string id = "";
            int icount = 0;
            int ierr = 0;
            var idsArray = idsStr.Substring(0, idsStr.Length - 1).Split(',');
            string[] arr = BaseUtil.GetStrArray(idsStr, ",");// 以;分割
            for (int i = 0; i < arr.GetLength(0); i++)
            {
                if (arr[i] != null)
                {
                    if (arr[i].ToString().Trim() != "")
                    {
                        id = arr[i].ToString().Trim();
                        string where = "where IndexId='" + id + "'";

                        if (ComService.GetTotal("TbIndex", where) > 0)
                        {
                            str += arr[i].ToString().Trim() + "录入指标删除失败！还有与其关联的录入表";
                        }
                        else
                        {
                            where = "where IndexId='" + id + "'";
                            if (IndexBasicService.DeleteByWhere(where))
                            {
                                icount++;
                            }
                            else
                            {
                                ierr++;
                            }
                        }
                    }
                }
            }

            if (ierr == 0)
            {
                string show = "成功删除" + icount.ToString() + "数据 " + str;
                return Json(SuccessTip(str));
            }
            else
            {
                string show = "成功删除" + icount.ToString() + "数据 " + " 删除失败" + ierr.ToString() + "数据 ";
                return Json(ErrorTip(show));
            }
        }
    }
}